package com.fyp.speachrecognition;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.StringTokenizer;

import com.fyp.MediaPlayer.MediaPlayerLibrary;
import com.fyp.settings.FileNames;
import com.fyp.settings.SettingsMain;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class SpeechDialer extends Activity implements OnInitListener
{
	private static final int VR_REQUEST = 999;
	private int MY_DATA_CHECK_CODE = 0;
    
	private ListView wordList;
	private final String LOG_TAG = "Speech Dialer";
	String Dial="tel:";

	boolean flag=true;
	int SAVE=1,CALL=2,Account=3,Dialer=4,PHONEBOOK=5;
	int action=0;
	MediaPlayer mrL = null;
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		Intent i=this.getIntent();
		Bundle b=i.getExtras();
		
		if(!((Boolean) b.get("Login_success")))
		{
			finish();
		}
		else
		{
			setContentView(R.layout.speech_dialer_activity);
		
			 mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.record_main_menu);
		
		
		
	    Button speechBtn = (Button) findViewById(R.id.speech_btn_dialerActivity);
	    wordList = (ListView) findViewById(R.id.sugestedWords);
	    PhoneCallListener phoneListener = new PhoneCallListener();
		TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
	    
	        speechBtn.setOnClickListener(new OnClickListener()
	        {
				public void onClick(View v) 
				{
					if(MediaPlayerLibrary.isPlaying())
					{
						mrL.stop();
						mrL.release();
						MediaPlayerLibrary.setPlaying(false);
					}
					
					Intent listenIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		        	listenIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
		        	listenIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say a word!");
		        	listenIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		        	listenIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
		            startActivityForResult(listenIntent, VR_REQUEST);
				}
	        	
	        });
		}

	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		  
	    if (requestCode == VR_REQUEST && resultCode == RESULT_OK) 
	    {
	        ArrayList<String> suggestedWords = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
	       wordList.setAdapter(new ArrayAdapter<String> (this, R.layout.word, suggestedWords));
	        ListIterator<String> it = suggestedWords.listIterator();
	        while(it.hasNext())
	        {
	        	String wordChosen = it.next();
	        	Log.v(LOG_TAG, "auto word chosen: "+wordChosen);
	        	wordChosen.trim();
	        	wordChosen=wordChosen.toLowerCase();
	        	if(wordChosen.equalsIgnoreCase("accounts")||wordChosen.equalsIgnoreCase("account"))
	        	{
	        		Log.v(LOG_TAG, "Account: "+wordChosen);
	        		action=Account;
	        		flag=false;
	        	}
	        	else if(wordChosen.equalsIgnoreCase("dialler")||wordChosen.contains("dialler"))
	        	{
	        		Log.v(LOG_TAG, "Dialer: "+wordChosen);
	        		action=Dialer;
	        		flag=false;
	        	}
	        	else if(wordChosen.contains("call")||wordChosen.contains("dial")||wordChosen.equals("phone"))
	        	{
	        		StringTokenizer st = new StringTokenizer(wordChosen," ");
	            	String s="";
	            	Dial="tel:";
	            	
	            	while(st.hasMoreTokens())
	            	{
	            		 
	            		 s= st.nextToken();
	            		 
	            		if(s.equalsIgnoreCase("call")||s.equalsIgnoreCase("dial")||s.equalsIgnoreCase("phone"))
	            		{
	            			
	            			Log.v(LOG_TAG, "Tokens: "+s);
	            			
	            			action=CALL;
	            			
	            		}
	            		else if(isInteger(s))
	            		{
	            			Log.v(LOG_TAG, "Tokens: "+s);
	            			Dial=Dial+s;
	            			
	            			flag=false;
	            			
	            		}
	            		else
	            		{
	            			Log.v(LOG_TAG, "Token (Error Block where No not found): "+s);
	            			Dial="tel:";
	            			flag=true;
	            			action=0;
	            			break;
	            		}
	            		
	            	}
	            	
	            }
	        	 else if(wordChosen.contains("number save")||wordChosen.contains("contact")||wordChosen.equalsIgnoreCase("save"))
	        	 {
	        		 Log.v(LOG_TAG, "Save: "+wordChosen);
	        		action=SAVE;
	        		flag=false;
	        	 }
	        	 else if(wordChosen.contains("phone book")||wordChosen.contains("phone list")||wordChosen.equalsIgnoreCase("delete"))
	        	 {
	        		 Log.v(LOG_TAG, "Phooke Bok: "+wordChosen);
		        		action=PHONEBOOK;
		        		flag=false;
	        	 }
	        	
	        	 
	        	if(!flag)
	        	{
	        		break;
	        	}
	        	
	        	
	        }
	        
	        if(action==CALL)
	        {
	        	Log.v(LOG_TAG, "Dial: "+Dial);
	        	Intent callIntent = new Intent(Intent.ACTION_CALL);
				callIntent.setData(Uri.parse(Dial));
				startActivity(callIntent);
				Dial="tel:";
	        }
	        else if(action==Dialer)
	        {
	        	Log.v(LOG_TAG, "from speachActivity calling to dialer activity: ");
	        	Intent i = new Intent(SpeechDialer.this, Dialer.class);
                startActivity(i);
	        }
	        else if (action==Account)
	        {
	        	Intent i = new Intent(SpeechDialer.this, ViewAccounts.class);
                startActivity(i);
	        }
	        else if(action==SAVE)
	        {
	        	 Intent i = new Intent(SpeechDialer.this, SaveContact.class);
	        	 i.putExtra("Login_success", true);
	                startActivity(i);
	        }
	        else if(action==PHONEBOOK)
	        {
	        	 Intent i = new Intent(SpeechDialer.this, DeleteContactActivity.class);
	        	 i.putExtra("Login_success", true);
	                startActivity(i);
	        }
	        else if(action==0)
	        {
	        	 mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.no_keyword_match);
	        	Toast.makeText(SpeechDialer.this, "No Key Word Matches", Toast.LENGTH_SHORT).show();
	        }
	        
	    }
	    
	  
	    super.onActivityResult(requestCode, resultCode, data);
	}
	public static boolean isInteger(String s) 
	{
	    try { 
	        Integer.parseInt(s); 
	    } catch(NumberFormatException e) { 
	        return false; 
	    }
	    // only got here if we didn't return false
	    return true;
	}
	
	public void onInit(int initStatus) 
	{ 
		//if successful, set locale
		 
		//*choose your own locale here***
		   
	}
	public class PhoneCallListener extends PhoneStateListener {
		 
		private boolean isPhoneCalling = false;
	
		String LOG_TAG = "LOGGING 123";
	
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
	
			if (TelephonyManager.CALL_STATE_RINGING == state) {
				// phone ringing
				Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
			}
	
			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				// active
				Log.i(LOG_TAG, "OFFHOOK");
	
				isPhoneCalling = true;
			}
	
			if (TelephonyManager.CALL_STATE_IDLE == state) {
				// run when class initial and phone call ended, 
				// need detect flag from CALL_STATE_OFFHOOK
				Log.i(LOG_TAG, "IDLE");
	
				if (isPhoneCalling) {
	
					Log.i(LOG_TAG, "restart app");
					Intent i = new Intent(getBaseContext(), SpeechDialer.class);
	            
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					i.putExtra("Login_success", true);
					startActivity(i);
					
	
					isPhoneCalling = false;
				}
	
			}
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.Configuration:
	            record();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	private void record() {
		// TODO Auto-generated method stub
		Intent i = new Intent(getApplicationContext(), SettingsMain.class);
		startActivity(i);
	}


}
